/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmProjectMilepostController 项目策划-里程碑及任务
 * <p>
 * 修改纪录 2021-01-06 版本：1.0 wudaliang 创建。
 *
 * @version 版本：1.0
 * @author 作者：wudaliang 创建日期：2021-01-06
 */

package com.topscomm.mpm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmMilePostTemplateEntity;
import com.topscomm.mpm.pojo.MpmProjectMilepostEntity;
import com.topscomm.mpm.pojo.MpmProjectTaskEntity;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.pub.util.*;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.mpm.controller.auto.MpmProjectMilepostControllerAuto;
import com.topscomm.pub.vo.ResponseResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: wudaliang
 * @date: 2021-01-06
 * @description:项目策划-里程碑及任务Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectMilepost")
public class MpmProjectMilepostController extends MpmProjectMilepostControllerAuto implements
    IMpmProjectMilepostController {

    private Logger logger = LoggerFactory.getLogger(MpmProjectPolymerizationController.class);

    @Autowired
    private MpmProjectPlanService mpmProjectPlanService;

    @Autowired
    private MpmMilePostTemplateService mpmMilePostTemplateService;
    @Autowired
    private MpmProjectMilepostService mpmProjectMilepostService;

    @Autowired
    private MpmProjectTaskService mpmProjectTaskService;

    @Autowired
    private MpmIndexController mpmIndexController;
    @Autowired
    private MpmProjectService mpmProjectService;


    /**
     * @param paraMap
     * @return
     * @author: wudaliang
     * @date: 2021-01-06
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_planid")) {
            String value = paraMap.get("qry_planid").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and planid = '{0}' ", value);
            }
        }
        //按照项目名称或编号查询
        if (paraMap.containsKey("qry_projectstr")) {
            String value = paraMap.get("qry_projectstr").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(
                    " and EXISTS (SELECT PROJECTCODE from MPMPROJECT where MPMPROJECT.PROJECTCODE=MPMPROJECTMILEPOST.PROJECTCODE and  (PROJECTNAME like '%{0}%' or PROJECTCODE = '{0}'))  ",
                    value);
            }
        }
        //按照责任人名称或工号查询
        if (paraMap.containsKey("qry_responsiblestr")) {
            String value = paraMap.get("qry_responsiblestr").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and (RESPONSIBLE like '%{0}%' or RESPONSIBLECODE ='{0}' )",
                    value);
            }
        }
        if (paraMap.containsKey("qry_operatecode")) {
            String value = paraMap.get("qry_operatecode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and operatecode = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_projectcode")) {
            String value = paraMap.get("qry_projectcode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and projectcode = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_operatecode")) {
            String value = paraMap.get("qry_operatecode").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and operatecode = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_id")) {
            String value = paraMap.get("qry_id").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and id = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_milepoststate")) {
            String value = paraMap.get("qry_milepoststate").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and milepoststate = {0} ", value);
            }
        }
        if (paraMap.containsKey("qry_enabled")) {
            String value = paraMap.get("qry_enabled").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and enabled = {0} ", value);
            }
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and state = {0} ", value);
            }
        }
        if (paraMap.containsKey("qry_overdue")) {
            sql.appendSingle(" and  PLANFINISHTIME < {0} ",
                SQLAdapter.toDateShort(DateUtil.formatDate(new Date())));
        }
        if (paraMap.containsKey("qry_permission")) {
            String value = paraMap.get("qry_permission").toString();
            sql.appendSingle("and " + mpmProjectService.whereExistsSqlForIndex("MpmProjectMilePost", "projectcode", value));
        }
        // 所属策划单审批状态
        if (paraMap.containsKey("qry_planapprovalstate")) {
            String value = paraMap.get("qry_planapprovalstate").toString();
            sql.appendSingle("and exists (select 1 from MpmProjectPlan p where " +
                    "MpmProjectMilePost.planid = p.id and p.state in ({0}))", value);
        }
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and milepostname like '%{0}%' ", value);
            }
        }
        if (paraMap.containsKey("queryType")) {
            String value = ConvertUtil.convertToString(paraMap.get("queryType"));
            if ("0".equals(value)) {
                sql.appendSingle(" and planfinishtime < {0} - 1 ", SQLAdapter.getDate());
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: wudaliang
     * @date: 2021-01-06
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        if (paraMap.get("viewAllMilePost").equals("true")) {
            return super.refList(paraMap);
        } else {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellRefListSql(paraMap);
            StringBufferProxy str = new StringBufferProxy();
            str.appendSingle("{0} and responsiblecode = {1}", sqlWhere, ConvertUtil.convertToString(paraMap.get("currentUser")));
            int totalCount = this.service.getCount(str.toString());
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(str.toString(), query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = this.service.queryMapByWhere(str.toString());
            }

            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        }
    }

    /**
      * @description:
      * @author 范智明
      * @param paraMap
      * @return ResponseResult
      * @date 2021/6/28
      * @modify 辛福朔 添加初始里程碑及任务添加
      */
    @PostMapping(value = "/insertBatch")
    public ResponseResult<Object> insertBatch(
        @RequestBody(required = false) Map<String, Object> paraMap) {
            this.service.insertBatch(paraMap);
            return ResponseResult.ok(paraMap);
    }


    /**
     * @author: wudaliang
     * @date: 2021-01-21
     * @param: paraMap
     * @description: 按照项目添加里程碑及任务
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @PostMapping(value = "/insertFromProject")
    public ResponseResult<Object> insertFromProject(
        @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            ResponseResult responseResult = mpmProjectMilepostService.insertFromProject(paraMap);
            return responseResult;
        } catch (Exception ex) {
            return ResponseResult.error("插入里程碑及任务出错，请联系管理员!");
        }
    }


    /**
     * @author: wudaliang
     * @date: 2021-01-21
     * @param: paraMap
     * @description: 按照模板添加里程碑及任务
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @PostMapping(value = "/insertFromMilePostTemplate")
    public ResponseResult<Object> insertFromMilePostTemplate(
        @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            ResponseResult responseResult = mpmProjectMilepostService
                .insertFromMilePostTemplate(paraMap);
            return responseResult;
        } catch (Exception ex) {
            logger.info(ex.getMessage());
            return ResponseResult.error("插入里程碑及任务出错，请联系管理员!");
        }
    }


    /**
     * @author: wudaliang
     * @date: 2021-01-29
     * @param: dataMap
     * @param: paraMap
     * @description: 修改新的策划书中从老策划书带过来的旧版里程碑及任务后，回写旧版里程碑及任务下的任务中的里程碑及任务名称
     * @return: void
     * @modify:
     */
    @Override
    protected void afterUpdate(Map<String, Object> dataMap, Map<String, Object> paraMap)
        throws Exception {
        super.afterUpdate(dataMap, paraMap);
        Long operatecode = (long) paraMap.get("operatecode");
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("milepostcode  = {0}", operatecode);
        List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService
            .queryByWhere(sql.toString());
        List<BasicEntity> batchUpdate = new ArrayList<BasicEntity>();
        if (mpmProjectTaskEntities.size() > 0) {
            for (MpmProjectTaskEntity e : mpmProjectTaskEntities) {
                e.setMilepostname(paraMap.get("milepostname").toString());
                batchUpdate.add(e);
            }
        }
        mpmProjectTaskService.updateBatch(batchUpdate);
    }

    /**
     * @author: hudeyong
     * @date: 2021-01-29
     * @param: dataMap
     * @param: paraMap
     * @description: 加载里程碑及任务相关信息
     * @return: void
     * @modify:
     */
	@GetMapping(value = "/milepostLoadInfo")
	public ResponseResult<Object> milepostLoadInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		String planid = ConvertUtil.convertToString(paraMap.get("id"));
		StringBufferProxy sql = new StringBufferProxy();
		// 修改默认排序字段为planfinishtime(计划达成日期)
		sql.appendSingle("planid = {0} order by sortcode asc,planfinishtime asc,id asc",planid);
        List<Map<String,Object>> milepostList = new ArrayList<>();
        // 获取里程碑及任务信息
		List<MpmProjectMilepostEntity> milepostEntities = this.service.queryByWhere(sql.toString());
		// 如果没有里程碑及任务信息，直接return
		if(milepostEntities.size() <= 0) {
            paraMap.put("milepostList", milepostList);
            return ResponseResult.ok(paraMap);
        }
        String milepostcodeStr = milepostEntities.stream().map(item -> "'" + ConvertUtil.convertToString(item.getOperatecode()) + "'").collect(Collectors.joining(","));
        sql.clear();
        sql.appendSingle("milepostcode in ({0}) and taskstate > 0",milepostcodeStr);
        // 获取里程碑及任务下的所有非未开始任务信息
        List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
        // 将任务信息按照里程碑及任务进行分类
        Map<String,List<MpmProjectTaskEntity>> mpmProjectTaskMap = mpmProjectTaskEntities.stream().collect(Collectors.groupingBy(MpmProjectTaskEntity::getMilepostcode));
        milepostEntities.stream().forEach(item -> {
            Map<String,Object> milepostmap = item.convertToMap();
            // 判断里程碑及任务是否为模板里程碑及任务
            this.beforeLoadInfo(milepostmap);
            String milepostcode = ConvertUtil.convertToString(item.getOperatecode());
            // 如果该里程碑及任务没有任务或任务都没有开始，允许用户删除此里程碑及任务
                if(mpmProjectTaskMap.get(milepostcode) == null) {
                    milepostmap.put("enableDelete",true);
                } else {
                    milepostmap.put("enableDelete",false);
                }
                milepostList.add(milepostmap);
        });
		paraMap.put("milepostList", milepostList);
		return ResponseResult.ok(paraMap);
    }
    /**
     * @description:
     * @author xinfushuo
     * @param entityMap 里程碑及任务entity转化的map
     * @date 2021/10/19
     * @modify
     */
    private void beforeLoadInfo(Map<String,Object> entityMap ){
        MpmMilePostTemplateEntity template = mpmMilePostTemplateService.queryById(ConvertUtil.convertToString(entityMap.get("sourceid")));
        if(template!=null){
            entityMap.put("templatetype", template.getType());
        }

    }
    /**
     * @author: hudeyong
     * @date: 2021-01-29
     * @param: dataMap
     * @param: paraMap
     * @description: 保存全部里程碑及任务
     * @return: void
     * @modify:
     */
	@PostMapping(value = "/updateInfo")
    public ResponseResult<Object> updateInfo(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            JSONArray jsonArray = (JSONArray) paraMap.get("milepostList");
            List<Map> milepostList = JSONObject.parseArray(jsonArray.toJSONString(), Map.class);
        	String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        	String planid = ConvertUtil.convertToString(paraMap.get("planid"));
        	List<BasicEntity> batchInsert = new ArrayList<BasicEntity>();
        	List<Map<String,Object>> batchUpdate = new ArrayList<Map<String,Object>>();
        	List<BasicEntity> basicTaskEntities = new ArrayList<>();
        	for(Map<String, Object> map : milepostList) {
        		if(map.containsKey("milepostcode")) {
        		    // 如果是复制后未修改的进行判断查看是否修改
        		    this.updateCopyEdit(map);
                    batchUpdate.add(map);
                    // 同步更新任务的里程碑名称
                    List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.updateTaskname(map);
                    if (!CollectionUtil.isEmpty(mpmProjectTaskEntities)) {
                        basicTaskEntities.addAll(mpmProjectTaskEntities);
                    }
        		}else {
        			map.put("id", "");
        			map.put("projectcode", projectcode);
        			map.put("planid", planid);
        			BasicEntity milepostEntity = new MpmProjectMilepostEntity();
        			milepostEntity = milepostEntity.convertFromMap(map);
                    batchInsert.add(milepostEntity);
        		}
        	}
        	this.service.insertBatch(batchInsert);
        	this.service.updateBatchMap(batchUpdate);
        	mpmProjectTaskService.updateBatch(basicTaskEntities);
            return ResponseResult.ok("ok");
        } catch (Exception ex) {
            return ResponseResult.error("插入里程碑及任务出错，请联系管理员!");
        }
    }

    /***
     * @description: 判断复制的里程碑是否发生改变
     * @param map
     * @return void
     * @author: wangxinhua
     * @date: 2022/9/14 16:01
     * @modify:
     */
    private void updateCopyEdit(Map<String, Object> map) {
        // 如果是复制后未修改的进行判断查看是否修改
        if(ConvertUtil.convertToString(MpmSystemConst.EnableEnum.Unenabled).equals(map.get(MpmProjectMilepostEntity.FieldCopyedit))) {
            //定义比较的字段
            List<String> compareFields = Arrays.asList(MpmProjectMilepostEntity.FieldMilepostname,MpmProjectMilepostEntity.FieldDeliverable);
            //获取复制源头信息
            Map<String,Object> copyFromMap = this.service.queryMapById(ConvertUtil.convertToString(map.get(MpmProjectMilepostEntity.FieldCopysourceid)));
            boolean isSame = true;
            //进行比较
            for(String field : compareFields) {
                if(!(ConvertUtil.convertToString(copyFromMap.get(field)).equals(ConvertUtil.convertToString(map.get(field))))){
                    isSame = false;
                    break;
                }
            }
            // 如果不相同，更新copyedit
            if (!isSame) {
                map.put(MpmProjectMilepostEntity.FieldCopyedit, ConvertUtil.convertToString(MpmSystemConst.EnableEnum.Enabled));
            }
        }
    }

    /**
     * @author: hudeyong
     * @date: 2021-01-29
     * @param: dataMap
     * @param: paraMap
     * @description: 保存某个里程碑及任务
     * @return: void
     * @modify:
     */
	@PostMapping(value = "/saveMilepost")
    public ResponseResult<Object> saveMilepost(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
        	Map<String, Object> milepost = (Map<String, Object>) paraMap.get("milepost");
        	String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        	String planid = ConvertUtil.convertToString(paraMap.get("planid"));
    		if(milepost.containsKey("id")) {
    			this.service.updateByWhere(milepost, "id = "+ ConvertUtil.convertToString(milepost.get("id")));
    		}else {
    			milepost.put("id", "");
    			milepost.put("newadd", "1");
    			milepost.put("projectcode", projectcode);
    			milepost.put("planid", planid);
    			BasicEntity milepostEntity = new MpmProjectMilepostEntity();
    			milepostEntity = milepostEntity.convertFromMap(milepost);
    			this.service.insert(milepostEntity);
    			return ResponseResult.ok(milepostEntity);
    		}
            return ResponseResult.ok("ok");
        } catch (Exception ex) {
            return ResponseResult.error("插入里程碑及任务出错，请联系管理员!");
        }
    }

    @PostMapping(value = "/updateMilepostBatch")
    public ResponseResult<Object> updateMilepostBatch(@RequestBody(required = false) Map<String, Object> paraMap){

            List<Map<String, Object>> milepostList = (List<Map<String, Object>>) paraMap.get("milepostList");
            ArrayList<BasicEntity> basicEntities = new ArrayList<>();
            milepostList.forEach(item->{
                BasicEntity milepostEntity = new MpmProjectMilepostEntity();
                milepostEntity = milepostEntity.convertFromMap(item);
                basicEntities.add(milepostEntity);
            });
            this.service.updateBatch(basicEntities);
            return ResponseResult.ok("ok");
    }
    /**
      * @description:
      * @author xinfushuo
      * @param
      * @throws
      * @return
      * @date 2021/10/18
      * @modify
      */
    @Override
    @GetMapping(value = "/dataCodeList")
    public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        Map<String, Object> codeMap = new HashMap<String, Object>();
        List<Map<String, Object>> projectlevelList = datacodeCache.getCodeListMap("MpmProjectLevel", "", "sortcode");
        codeMap.put("projectlevelList", projectlevelList);
        List<Map<String, Object>> projecttypeList = datacodeCache.getCodeListMap("MpmProjectType", "", "sortcode");
        codeMap.put("projecttypeList", projecttypeList);
        List<Map<String, Object>> enabledList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
        codeMap.put("enabledList", enabledList);
        super.dataCodeList(paraMap);
        return ResponseResult.ok(codeMap);
    }
    /**
      * @description: 获取标前引导的里程碑及任务
      * @author xinfushuo
      * @param paraMap :  projectcode
      * @throws
      * @return
      * @date 2021/10/18
      * @modify
      */
    @GetMapping(value = "/bidGuideList")
    public ResponseResult<Object> bidGuideList(@RequestParam(required = false) Map<String,Object> paraMap){
        if(paraMap.get("projectcode")!=null) {
            String projectCode = ConvertUtil.convertToString(paraMap.get("projectcode"));
            List<Map<String, Object>> dataList = this.service.queryTaskListForBidGuide(projectCode);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("dataList", dataList);
            return ResponseResult.ok(dataMap);
        }
        return ResponseResult.ok(paraMap);
    }
    /**
      * @description:
      * @author xinfushuo
      * @param
      * @throws
      * @return
      * @date 2021/10/19
      * @modify
      */
    @PostMapping(value = "/exportBidGuideExcel")
    public ResponseResult<Object> exportBidGuideExcel(@RequestBody(required = false) Map<String,Object> paraMap, HttpServletRequest request, HttpServletResponse response)  {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        String cols = ConvertUtil.convertToString(paraMap.get("cols"));
        String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
        fileName = fileName.length() == 0 ? "".concat(projectcode)+"标前引导.xlsx" : fileName + ".xlsx";
        InputStream inputStream = null;

        //获取inputstream
        List<Map<String,Object>> listDataMap = this.service.queryTaskListForBidGuide(projectcode);
        try {
             inputStream = OfficeOperateUtil.exportExeclXlsx(listDataMap, cols.split(","));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("istaskexport", "0");
            // 需要添加否则前台得不到istaskexport
            response.setHeader("Access-Control-Expose-Headers", "istaskexport");
            response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inputStream.close();
            return null;
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * @description:重写list
     * @author zhangjunyao
     * @param
     * @throws
     * @return ResponseResult
     * @date 2021/12/10
     * @modify
     */
    @Override
    @GetMapping({"/list"})
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            int totalCount = this.service.getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = this.service.queryMapByWhere(sqlWhere);
            }
            if (CollectionUtils.isEmpty(tempList)) {
                return ResponseResult.ok(new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage()));
            }
            // 项目追踪模块下里程碑及任务需要查询督办情况
            if (paraMap.containsKey("qry_superviselist")) {
                this.service.getSuperviseList(tempList, ConvertUtil.convertToString(paraMap.get("qry_projectcode")));
            }
            // 超期里程碑及任务需要查询项目相关信息与未完成任务
            if (paraMap.containsKey("qry_overdue")) {
                this.service.getProjectInfo(tempList);
                this.service.getUnfinishedTask(tempList);
            }
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    /***
     * @description: 获取策划可套用之前项目的里程碑以及任务信息
     * @param paraMap
     * @return com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author: wangxinhua
     * @date: 2022/9/14 16:02
     * @modify:
     */
    @GetMapping(value = "/getMilePostForOldProjectAdd")
    public ResponseResult<Object> getMilePostForOldProjectAdd(@RequestParam(required = false) Map<String, Object> paraMap) {
        List<Map<String,Object>> milePostList = new ArrayList<Map<String,Object>>();
        String projectCode = ConvertUtil.convertToString(paraMap.get("code"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}' and enabled=1 and state=9 ",projectCode);
        List<Map<String,Object>> planList = new ArrayList<Map<String,Object>>();
        planList = mpmProjectPlanService.queryMapByWhere(sql.toString());
        if(planList.size()>0) {
            sql.clear();
            sql.appendSingle("planid = {0} and enabled=1  order by sortcode asc,planfinishtime asc,id asc ",planList.get(0).get("id"));
            milePostList = mpmProjectMilepostService.queryMapByWhere(sql.toString());
            for(Map<String,Object> milePost : milePostList) {
                sql.clear();
                sql.appendSingle("milepostcode = {0} and enabled=1 order by sortcode asc,planenddate asc,planstartdate asc,id asc ",milePost.get("operatecode"));
                List<Map<String,Object>> taskList = mpmProjectTaskService.queryMapByWhere(sql.toString());
                milePost.put("tasklist", taskList);
            }
        }
        return ResponseResult.ok(milePostList);
    }

    /***
     * @description: 保存套用信息
     * @param paraMap
     * @return com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author: wangxinhua
     * @date: 2022/9/14 16:02
     * @modify:
     */
    @PostMapping(value = "/saveOldProjectInfo")
    public ResponseResult<Object> saveOldProjectInfo(@RequestBody(required = false) Map<String, Object> paraMap) {
        this.service.saveOldProjectInfo(paraMap);
        return ResponseResult.ok("成功");
    }
    /***
     * @description: 保存套用信息
     * @param paraMap
     * @author: houyuhang
     * @date: 2023/02/13
     * @modify:
     */
    @GetMapping(value= "/queryMaxTaskDate")
    public ResponseResult<Object> queryMaxTaskDate(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            StringBufferProxy sql = new StringBufferProxy();
            if (paraMap.containsKey("qry_milepostcode")) {
                sql.appendSingle(" milepostcode = '{0}' and enabled = 1 order by planenddate desc ", ConvertUtil.convertToString(paraMap.get("qry_milepostcode")));
            }
            List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
            if (CollectionUtil.isEmpty(mpmProjectTaskEntities)) {
                return ResponseResult.ok(new HashMap<>());
            }
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("maxdate", mpmProjectTaskEntities.get(0).getPlanenddate());
            return ResponseResult.ok(resMap);
        } catch (Exception ex) {
            return this.handleControllerException(ex);
        }
    }
    /**
     * @description: // 导入数据处理
     * @param: [excelFile, paraMap]
     * @return:
     * @author: houyuhang
     * @date: 2022/11/14 10:10
     * @modify:
     */
    @PostMapping(value = "/importExcel")
    public ResponseResult<Object> importExcel(@RequestParam("file") MultipartFile excelFile,
                                              @RequestParam(required = false) Map<String, Object> paraMap) {
        // 得到文件流
        File file = FileUtil.multipartFileToFile(excelFile);
        try {
            // 导入文件流，将内容
            int res = this.service.executeImportDataExcel(paraMap, file);
            return ResponseResult.ok("导入成功！");
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage(), true);
        }
    }
}

